<template>
  <transition name="el-zoom-in-top">
    <el-form
      :ref="'formRuleData' + index"
      :key="source.propId"
      :rules="formRuleRules"
      :model="source"
      label-width="96px"
      label-suffix="："
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input
              v-if="drawerType !== 'view'"
              v-model="source.ruleName"
              class="w360 show-word-limit"
              maxlength="50"
              show-word-limit
              placeholder="请输入规则名称"
            />
            <span v-else class="fontBold">{{ source.ruleName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则备注" prop="ruleRemark">
            <el-input
              v-if="drawerType !== 'view'"
              v-model="source.ruleRemark"
              class="w360 show-word-limit-52"
              maxlength="255"
              show-word-limit
              placeholder="请输入规则备注"
            />
            <span v-else class="fontBold">{{ source.ruleRemark }}</span>
            <el-popconfirm
              title="其他规则前置规则引用了本条规则的话，其前置规则将被置空，确定删除吗？"
              @confirm="handleClick('del', index)"
            >
              <el-button v-if="drawerType !== 'view'" slot="reference" class="carryBtn">删除规则</el-button>
            </el-popconfirm>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="ruleBottom">
        <el-col :span="12">
          <el-form-item label="前置规则" prop="prepositionRuleData">
            <el-select
              v-if="drawerType !== 'view'"
              v-model="source.prepositionRuleData.propId"
              clearable
              class="w360"
              @change="(val) => handleChangePrepositionRule(val, index)"
            >
              <el-option
                v-for="row in prepositionRuleList.filter((row) => {
                  return (
                    row.propId != source.propId && !getPrepositionRuleArr(source.propId, []).includes(row.propId)
                  )
                })"
                :key="row.propId"
                :label="row.label"
                :value="row.propId"
              ></el-option>
            </el-select>
            <span v-else class="fontBold">{{ source.prepositionRuleName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="条件关系" prop="conditionalRelation">
            <el-select v-if="drawerType !== 'view'" v-model="source.conditionalRelation" clearable class="w360">
              <el-option
                v-for="row in conditionalRelationOption"
                :key="row.value"
                :label="row.label"
                :value="row.value"
              ></el-option>
            </el-select>
            <span v-else class="fontBold">{{ source.conditionalRelationName }}</span>
          </el-form-item>
        </el-col>
        <el-table :data="source.conditionDataList" class="conditionTable">
          <el-table-column type="index" width="100" label="条件序号" align="center"></el-table-column>
          <el-table-column v-if="type === 'file'" prop="description" label="条件描述" width="300">
            <template slot-scope="scope">
              <el-input
                v-if="drawerType !== 'view'"
                v-model="scope.row.description"
                class="show-word-limit-52"
                maxlength="255"
                show-word-limit
                placeholder="请输入条件描述"
              />
              <template v-else>{{ scope.row.description }}</template>
            </template>
          </el-table-column>
          <el-table-column prop="conditionContent" label="条件内容">
            <template slot-scope="scope">
              <template v-if="type === 'parameterConfigure'">
                <div class="conditionContent">
                  <el-tooltip effect="dark" :content="scope.row.factModeName" placement="top-start">
                    <el-input
                      v-model="scope.row.factModeName"
                      class="conditionInput"
                      :disabled="drawerType === 'view'"
                      placeholder="请输入事实方式"
                    />
                  </el-tooltip>
                  <el-input
                    v-model="scope.row.comparator"
                    class="conditionInput comparatorInput"
                    :disabled="drawerType === 'view'"
                    placeholder="请输入比较符"
                  />
                  <el-tooltip effect="dark" :content="scope.row.standardSpecification" placement="top-start">
                    <el-input
                      v-model="scope.row.standardSpecification"
                      class="conditionInput"
                      :disabled="drawerType === 'view'"
                      placeholder="请输入标准规范"
                    />
                  </el-tooltip>
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column v-if="drawerType !== 'view'" fixed="right" label="操作" width="160">
            <template slot-scope="scope">
              <el-popconfirm title="确定删除吗？" @confirm="handleClick('conditionDel', index, scope.$index)">
                <el-link slot="reference" class="conditionDel" type="primary" :underline="false">删除</el-link>
              </el-popconfirm>

              <el-link
                type="primary"
                :underline="false"
                @click.native.prevent="handleClick('conditionCopy', index, scope.$index)"
              >
                复制
              </el-link>
              <el-link
                type="primary"
                :underline="false"
                @click.native.prevent="handleClick('conditionMoveUp', index, scope.$index)"
              >
                上移
              </el-link>
              <el-link
                type="primary"
                :underline="false"
                @click.native.prevent="handleClick('conditionMoveDown', index, scope.$index)"
              >
                下移
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          v-if="drawerType !== 'view'"
          type="text"
          style="padding-left: 14px; margin-top: 3px"
          icon="el-icon-plus"
          @click="handleClick('conditionAdd', index)"
        >
          添加条件
        </el-button>
        <el-form-item v-if="type === 'file'" label="测试结论" prop="testResult" class="testResult">
          如果满足条件 输出：
          <span class="success result">通过</span>
          如果不满足条件 输出：
          <span class="fail result">不通过</span>
          不满足条件X:（条件内容）
          <!-- 不满足条件“{{ source.ruleName }}” -->
        </el-form-item>
        <template v-else>
          <el-form-item label="满足条件" prop="testResult" class="testResult">
            {{
              source.type === 1
                ? source.ruleName.replace(/依赖规则/, '可配置')
                : source.ruleName.replace(/配置规则/, '配置通过')
            }}
          </el-form-item>
          <el-form-item label="不满足条件" prop="testResult" class="testResult">
            {{
              source.type === 1
                ? source.ruleName.replace(/依赖规则/, '不可配置')
                : source.ruleName.replace(/配置规则/, '配置不通过')
            }}
          </el-form-item>
        </template>
      </el-row>
    </el-form>
  </transition>
</template>
<script>
import { randomString } from '@/utils/index'
import { ConditionalType } from '@/utils/enum/index'
export default {
  name: 'ItemComponent',
  props: {
    index: {
      type: Number,
      default: null
    }, // 每一行的索引
    source: {
      type: Object,
      default() {
        return {}
      }
    },
    type: {
      type: String,
      default: 'file'
    },
    drawerType: {
      type: String,
      default: 'view'
    },
    prepositionRuleList: {
      type: Array,
      default: () => {
        return []
      }
    }, // 绑定的值
    formData: {
      type: Object,
      default: () => {
        return {}
      }
    } // 右侧是否显示绑定的值
  },
  data() {
    let self = this
    return {
      ConditionalType: ConditionalType,
      formRuleRules: {
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' },
          { validator: self.validateRuleName, trigger: 'blur' }
        ],
        conditionalRelation: [{ required: true, message: '请选择条件关系', trigger: ['blur', 'change'] }]
      }
    }
  },
  methods: {
    validateRuleName(rule, value, callback) {
      let count = 0
      this.formData.ruleDataList.forEach((item) => {
        if (item.ruleName === value) {
          count++
        }
      })
      if (count > 1) {
        callback(new Error('规则名称重复'))
      } else {
        callback()
      }
    },
    handleClick(name, index, conditionIndex) {
      let conditionDataList = []
      if (name.indexOf('condition') != -1) {
        conditionDataList = this.formData.ruleDataList[index].conditionDataList
      }
      switch (name) {
        case 'add':
          this.formData.ruleDataList.push({
            propId: randomString(11),
            ruleName: '',
            ruleRemark: '',
            prepositionRuleData: {},
            conditionalRelation: 1,
            conditionDataList: []
          })
          break
        case 'del':
          this.formData.ruleDataList.splice(index, 1)
          break
        case 'conditionAdd':
          conditionDataList.push({
            description: '',
            factMode: [],
            comparator: '',
            enterValue: '',
            standardSpecification: []
          })
          break
        case 'conditionDel':
          conditionDataList.splice(conditionIndex, 1)
          break
        case 'conditionCopy':
          conditionDataList.push({ ...conditionDataList[conditionIndex], conditionId: undefined })
          break
        case 'conditionMoveUp':
          if (conditionIndex === 0) return
          this.handlePositionSwap(conditionDataList, conditionIndex - 1, conditionIndex)
          break
        case 'conditionMoveDown':
          if (conditionIndex === conditionDataList.length - 1) return
          this.handlePositionSwap(conditionDataList, conditionIndex, conditionIndex + 1)
          break
      }
    },
    handlePositionSwap(arr, i, j) {
      let obj = JSON.parse(JSON.stringify(arr[i]))
      arr.splice(i, 1, arr[j])
      arr.splice(j, 1, obj)
    },
    getPrepositionRuleArr(propId, arr) {
      this.formData.ruleDataList.forEach((item) => {
        if (item.prepositionRuleData.propId === propId) {
          arr.push(item.propId)
          this.getPrepositionRuleArr(item.propId, arr)
        }
      })
      return arr
    },
    // 事实方式
    handleChangeFactMode(val, index, conditionIndex) {
      if (val.length === 0) {
        this.formData.ruleDataList[index].conditionDataList[conditionIndex].nearestFactMode = undefined
        this.formData.ruleDataList[index].conditionDataList[conditionIndex].comparator = undefined
        this.formData.ruleDataList[index].conditionDataList[conditionIndex].standardSpecification = []
      } else {
        let arr = []
        let obj = this.factModeObj
        val.forEach((item) => {
          obj = obj[item]
          arr.push(obj.type + '-' + obj.value)
        })
        let row = this.formData.ruleDataList[index].conditionDataList[conditionIndex]
        let len = arr.length
        for (let i = len - 1; i >= 0; i--) {
          if (arr[i].indexOf('1-') != -1) {
            let nearestFactMode = arr[i].split('-')[1]
            row.nearestFactMode = nearestFactMode
            if (this.factModeToComparatorOption[nearestFactMode]) {
              let comparatorOption = this.factModeToComparatorOption[nearestFactMode].map((item) => {
                return item.value
              })
              if (!comparatorOption.includes(row.comparator)) {
                row.comparator = undefined
                row.standardSpecification = []
              } else {
                this.handleChangeComparator(row.comparator, index, conditionIndex)
              }
            }
            break
          }
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.w360 {
  width: 360px;
}
.show-word-limit {
  /deep/.el-input__inner {
    padding-right: 45px;
  }
}
.show-word-limit-52 {
  /deep/.el-input__inner {
    padding-right: 52px;
  }
}
.carryBtn {
  position: absolute;
  right: 24px;
}
.ruleBottom {
  background-color: #f5f7fa;
  padding: 24px 10px 6px;
  .conditionTable {
    background-color: #f5f7fa;
    /deep/tr,
    /deep/th,
    /deep/td {
      background-color: #f5f7fa;
      border: none !important;
    }
    /deep/.el-table__fixed::before,
    /deep/.el-table__fixed-right::before {
      background-color: #f5f7fa;
    }
    .el-link + .el-link {
      margin-left: 0;
    }

    .conditionDel {
      padding-left: 0;
    }
  }
  .conditionTable::before {
    background-color: #f5f7fa;
  }
  .conditionContent {
    display: flex;
    align-items: center;
    .treeItem {
      width: 280px;
      background-color: #f5f7fa;
    }
    .comparatorContent {
      padding: 0 10px;
      width: 140px;
      text-align: center;
    }
    /deep/.conditionInput {
      margin-right: 10px;
      &.is-disabled .el-input__inner {
        cursor: pointer;
      }
    }
    .comparatorInput {
      width: 200px;
    }
  }
}

.testResult {
  margin-top: 6.5px;
  .result {
    border-radius: 12px 12px 12px 12px;
    opacity: 1;
    font-weight: 500;
    color: #ffffff;
    font-size: 12px;
    width: 56px;
    height: 22px;
    line-height: 22px;
    display: inline-block;
    text-align: center;
  }

  .success {
    background: #44ae74;
    // padding: 5px 16px;
    margin-right: 20px;
  }
  .fail {
    background: #ff0000;
    // padding: 5px 10px;
    margin-right: 10px;
  }
}
</style>
<style lang="scss">
// @import '@/styles/element-variables.scss';
.checkStrictlyPopper {
  .el-cascader-panel {
    .el-scrollbar .el-cascader-node:has(.hiddenPrefixIcon) {
      .el-radio,
      .el-checkbox {
        display: none;
      }
      .el-cascader-node__label {
        padding-left: 0;
      }
    }
  }
}

.cascaderView {
  .el-cascader-panel {
    .el-scrollbar {
      .el-checkbox,
      .el-icon-check {
        display: none;
      }
      .el-cascader-node__label {
        padding-left: 0;
      }

      .el-cascader-node.in-active-path,
      .el-cascader-node.is-selectable.in-checked-path,
      .el-cascader-node.is-active {
        color: #606266;
        font-weight: unset;
      }
    }
  }
}
</style>
